import React from 'react';
import {
  Button, Col, DatePicker, Drawer, Empty,
  Input, InputNumber, Layout, Modal, Popover, Radio,
  Row, Select, Tooltip, Tree, Upload,
} from 'antd';
import { Form, Icon } from '@ant-design/compatible';
import { connect } from 'dva';
import { PageHeaderLayout, StandardTable, SearchForm, IconButton, PageCard } from '../../components';
import { modalWidth, pageSize, apiUrl } from '../../../config';
import styles from './verify.css';
import moment from 'moment';
import Authorized from '../../utils/Authorized';
import tools from '../../utils';

const residTypeData = require('../../assets/stureg_web/static/area.json');
const ethnicData = require('../../assets/stureg_web/static/ethnic.json');
const types = require('../../assets/stureg_web/static/types.json');

const typeData = [];
for (let key in types) {
  typeData.push([key, types[key]]);
}

const reqApi = 'gather';
const { Sider, Content } = Layout;
const { TreeNode } = Tree;
const { Option } = Select;
const ethnicMapping = {};
const statusMapping = {
  5: '交费成功',
};
const situationMapping = {
  0: '应届',
  1: '往届',
};
const residTypeMapping = {};
residTypeData.map(item => {
  const { value, label, children } = item;
  residTypeMapping[value] = { label, children };
});
const residTypeMappingFull = {
  ...residTypeMapping,
  140402: { label: '潞州区' },
  140411: { label: '潞州区' },
  140421: { label: '上党区' },
  140424: { label: '屯留区' },
  140481: { label: '潞城区' },
};
let situationData = [];
const formItemLayout2 = {
  labelCol: { md: 6, xs: 7 },
  wrapperCol: { md: 18, xs: 17 },
};

class page extends React.Component {
  state = {
    currentNavi: [],
    currentTitle: '全部',
    loadingNavi: false,
    loadingContent: false,
    visible: false,
    visibleTree: false, // "系部和专业"树显隐
    record: {},
    selectedRows: [],
    searchs: [],
    pagination: {
      current: 1,
      pageSize,
      onShowSizeChange: (_, size) => {
        const { pagination } = this.state;
        pagination.pageSize = size;
      },
    },
    exporting: false,
    dialogTitle: "",
    formVisible: false, // 表单显隐
    dialogLoading: false, // 表单的提交按钮是否转圈
    visibleSearch: false,
    schoolData: [],
  };

  constructor(props) {
    super(props);

    ethnicData.map((item) => {
      const { value, label } = item;
      ethnicMapping[value] = label;
    });

    situationData = [];
    for (let value in situationMapping) {
      const label = situationMapping[value];
      situationData.push({ value, label });
    }
  }

  componentDidMount() {
    console.clear();
    this.funcGetNaviData();
  }

  // 获取菜单数据
  funcGetNaviData = () => {
    this.setState({ loadingNavi: true });

    const { props } = this;
    props.dispatch({
      type: reqApi + '/listSpecial',
      payload: {},
    }).then(() => {
      this.setState({ loadingNavi: false });
      this.funcGetListData();
    });
  };

  // 获取列表数据
  funcGetListData = () => {
    this.setState({
      loadingContent: true,
      selectedRows: [],
    });

    const { state } = this;
    const { searchs, pagination } = state;
    const { current, pageSize } = pagination;
    const { dispatch } = this.props;
    const payload = {
      currentPage: current,
      pageSize,
      searchs,
    };

    if (state.currentNavi.length)
      payload.specialIds = state.currentNavi + '';

    dispatch({
      type: reqApi + '/list',
      payload,
    }).then(() => this.setState({ loadingContent: false }));
  };

  // 树实体
  treeBody = (data) => {
    const nodes = [];

    for (let i = 0; i < data.length; i += 1) {
      const item = data[i];
      const { key, title, children, selectable, count, ids } = item;

      nodes.push(
        <TreeNode
          key={key}
          selectable={selectable}
          ids={ids}
          title={title + (count ? '：' + count + '人' : '')}
        >
          {this.treeBody(children || [])}
        </TreeNode>,
      );
    }
    return nodes;
  };

  // 导航菜单
  naviMenu = () => {
    const { props } = this;
    const data = props[reqApi].dataSpecial;

    if (data.length) {
      return (
        <div
          style={{
            maxHeight: 'calc(100vh - ' + (window.isMobile ? 56 : 120) + 'px)',
            overflow: 'auto',
          }}
        >
          <Tree
            blockNode
            defaultExpandAll
            onSelect={(selectedKeys, { selectedNodes }) => {
              const { ids, title } = selectedNodes.length ? selectedNodes[0] : {};
              this.setState({
                currentNavi: ids || selectedKeys,
                currentTitle: title || '全部',
                visibleTree: false,
              }, this.funcGetListData);
            }}
          >
            {this.treeBody(data)}
          </Tree>
        </div>
      );
    } else return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />;
  };

  // 弹出表格
  funcOpenTable = (record) => {
    const { id, name, specialName } = record;

    this.setState({
      record,
      visible: true,
      dialogTitle: (
        <div>
          <Icon type='solution' style={{ fontSize: 16 }} />
          <span> {'“' + name + '”的报名信息'}</span>
        </div>
      ),
    });

    const { dispatch } = this.props;

    dispatch({
      type: reqApi + '/echo',
      payload: { action: 'edit', id },
    }).then(() => {
      const { props } = this;
      const { echoModel } = props[reqApi];
      this.setState({
        record: {
          specialName,
          ...echoModel,
        },
      });
    });
  };

  // 弹出表单
  funcOpenForm = (record) => {
    const { id, specialId } = record;

    this.setState({
      record,
      formVisible: true,
    }, () => {
      const values = { ...record };
      const { props } = this;
      const pid = props[reqApi].mappingSpecialPID[specialId];
      if (pid) values.pid = pid;
      props.form.setFieldsValue(values);
    });

    const { dispatch } = this.props;
    dispatch({
      type: reqApi + '/echo',
      payload: { action: 'edit', id },
    }).then(() => {
      const { props } = this;
      const { echoModel } = props[reqApi];

      if (echoModel.idCardNum.length === 18) {
        const a = echoModel.idCardNum.substr(6, 8);
        let b = a.substr(0, 4) + '-';
        b += a.substr(4, 2) + '-' + a.substr(6);
        echoModel.birthday = moment(b, 'YYYY-MM-DD');
      }
      echoModel.sex = echoModel.sex ? '1' : '0';
      echoModel.lodging = echoModel.lodging ? '1' : '0';
      echoModel.specialId += '';
      echoModel.type += '';
      echoModel.situation += '';
      echoModel.residType += '';
      echoModel.citytown = echoModel.citytown ? '1' : '0';

      props.form.setFieldsValue(echoModel);
    });
  };

  // 撤销退学
  funcUndo = (id) => {
    const { dispatch } = this.props;

    dispatch({
      type: reqApi + '/exitUndo',
      payload: { studentId: id - 0 },
    }).then(() => {
      const { props } = this;
      const { success } = props[reqApi];
      if (success) this.funcGetListData();
    });
  };

  // 表格列
  columns = () => [
    {
      title: '学生姓名',
      dataIndex: 'name',
      fixed: true,
      width: 150,
      render: (text, record) => [
        <Authorized key='icon' authority={() => tools.funcCheckValid(this.props, 'edit')}>
          <a onClick={() => this.funcOpenForm(record)}>
            <Icon type='tool' className={styles.adjustIcon} title='调整信息' />
          </a>
        </Authorized>,
        <span key='print' className={styles.printBox}>
          <span
            className={record.exit === '0' ? styles.link : styles.link2}
            onClick={() => this.funcOpenTable(record)}
          >
            {text}
          </span>

          {record.exit === '1' ? (
            <Authorized authority={() => tools.funcCheckValid(this.props, 'exitUndo')}>
              <a onClick={() => this.funcUndo(record.id)}>
                <Icon type='undo' className={styles.printIcon} title='撤销退学' />
              </a>
            </Authorized>
          ) : null}

          <a onClick={() => this.funcPrint(record.id)}>
            <Icon
              type='printer'
              theme='twoTone'
              title='打印'
              className={styles.printIcon}
            />
          </a>
        </span>,
      ],
    },
    {
      title: '性别',
      dataIndex: 'sex',
      width: 50,
      render: text => text === '1' ? '男' : '女',
    },
    {
      title: '报考专业',
      dataIndex: 'specialName',
      width: 230,
    },
    {
      title: '是否住校',
      dataIndex: 'lodging',
      width: 80,
      render: text => text === '1' ? '住校' : '不住校',
    },
    {
      title: '所在居住地',
      dataIndex: 'residType',
      width: 100,
      render: value => residTypeMappingFull[value] ?
        residTypeMappingFull[value].label : '外地',
    },
    {
      title: '联系电话',
      dataIndex: 'phone',
      width: 120,
    },
    {
      title: "身份证号",
      dataIndex: "idCardNum",
      width: 180,
    },
    {
      title: "准考证号",
      dataIndex: "examCardNum",
      width: 130,
    },
    {
      title: '报名号',
      dataIndex: 'signup',
      width: 130,
    },
    {
      title: '中考成绩',
      dataIndex: 'sum',
      width: 80,
      render: text => text + '分',
    },
    {
      title: "家庭住址",
      dataIndex: "address",
    },
    {
      title: "毕业学校",
      dataIndex: "school",
      width: 150,
    },
    {
      title: '已交费日期',
      dataIndex: 'feeTime',
      width: 110,
      render: text => text.substr(0, 10),
    },
  ];

  // 记录查询表单提交
  funcOnSubmitSearch = searchs => {
    const { state } = this;
    state.pagination.current = 1; // 进行查询操作则将页码归一
    this.setState({
      searchs,
      visibleSearch: false,
    }, this.funcGetListData);
  };

  // 内容列表
  contentTable = () => {
    const { state, props } = this;
    const { data, counts } = props[reqApi];
    const {
      total,
      lodging1sex1,
      lodging1sex0,
      lodging0sex1,
      lodging0sex0,
      exitsex1,
      exitsex0,
    } = counts;
    const footerData = [];
    if (total) footerData.push('学生总数：' + total + '人');
    if (lodging1sex1) footerData.push('住校男生：' + lodging1sex1 + '人');
    if (lodging1sex0) footerData.push('住校女生：' + lodging1sex0 + '人');
    if (lodging0sex1) footerData.push('跑堂男生：' + lodging0sex1 + '人');
    if (lodging0sex0) footerData.push('跑堂女生：' + lodging0sex0 + '人');
    if (exitsex1) footerData.push('退学男生：' + exitsex1 + '人');
    if (exitsex0) footerData.push('退学女生：' + exitsex0 + '人');
    const footer = footerData.toString().replace(/,/g, '，');

    return (
      <div>
        <div style={{ display: 'inline-block', width: 'calc(100% - 100px)' }}>
          <Button.Group>
            {window.isMobile ? (
              <Button
                type='primary'
                style={{ marginBottom: 16 }}
                onClick={() => this.setState({ visibleTree: true })}
              >选择专业</Button>
            ) : (
              <IconButton
                text='打印'
                icon='printer'
                disabled={!total}
                style={{ marginBottom: 16 }}
                onClick={() => this.funcPrint()}
              />
            )}
            <IconButton
              text='导出'
              type={window.isMobile ? 'default' : 'primary'}
              loading={state.exporting}
              disabled={state.exporting || !total}
              onClick={this.funcExport}
              style={{ marginBottom: 16 }}
            />
            <Authorized authority={() => tools.funcCheckValid(props, 'delete')}>
              <IconButton
                text='删除'
                type='danger'
                disabled={!state.selectedRows.length}
                style={{ marginBottom: 16 }}
                onClick={this.funcDelete}
              />
            </Authorized>
            <Authorized authority={() => tools.funcCheckValid(props, 'exit')}>
              <IconButton
                text='退学'
                icon='logout'
                type='danger'
                disabled={!state.selectedRows.filter(record => record.exit === '0').length}
                style={{ marginBottom: 16 }}
                onClick={this.funcExit}
              />
            </Authorized>
          </Button.Group>
        </div>

        <div style={{ display: 'inline-block', width: 96, textAlign: 'right' }}>
          <IconButton
            text='查询'
            icon='more'
            onClick={() => this.setState({ visibleSearch: true })}
            style={{ marginBottom: 16 }}
          />
        </div>

        <StandardTable
          loading={state.loadingContent}
          columns={this.columns()}
          data={{
            list: data,
            pagination: { ...state.pagination, total },
          }}
          selectedRows={state.selectedRows}
          onSelectRow={(selectedRows) => this.setState({ selectedRows })}
          onChange={(pageParams) => {
            const { pagination } = this.state;
            pagination.current = pageParams.current;
            this.funcGetListData();
          }}
          scrollX={2000}
          fixedNum
          footer={footer}
        />
      </div>
    );
  };

  // 删除
  funcDelete = () => {
    const { state } = this;
    let names = [], ids = [];
    for (let i = 0; i < state.selectedRows.length; i += 1) {
      const item = state.selectedRows[i];
      const { id, name } = item;
      names.push(name);
      ids.push(id);
    }

    Modal.confirm({
      title: "删除?",
      content: (
        <div>
          <div>你即将删除以下记录：</div>
          <div>{names + ''}</div>
          <div>请确认是否删除？</div>
        </div>
      ),
      okText: "是",
      okType: "danger",
      cancelText: "否",
      onOk: () => {
        this.setState({ loading: true });

        const { dispatch } = this.props;
        dispatch({
          type: reqApi + '/dele',
          payload: { ids: ids + '' },
        }).then(() => {
          const { props } = this;
          const { success } = props[reqApi];
          if (success) this.funcGetListData();
          else this.setState({ loading: false });
        });
      },
    });
  };

  // 学生退学
  funcExit = () => {
    const { state } = this;
    const data = state.selectedRows.filter(record => record.exit === '0');
    let names = [], ids = [];
    for (let i = 0; i < data.length; i += 1) {
      const item = data[i];
      const { id, name } = item;
      names.push(name);
      ids.push(id);
    }

    Modal.confirm({
      title: "学生退学?",
      content: (
          <div>
            <div>你即将对以下学生进行退学：</div>
            <div>{names + ''}</div>
            <div>请确认是否继续？</div>
          </div>
      ),
      okText: "是",
      okType: "danger",
      cancelText: "否",
      onOk: () => {
        this.setState({ loading: true });

        const { dispatch } = this.props;
        dispatch({
          type: reqApi + '/exit',
          payload: { ids: ids + '' },
        }).then(() => {
          const { props } = this;
          const { success } = props[reqApi];
          if (success) this.funcGetListData();
          else this.setState({ loading: false });
        });
      },
    });
  };

  // 包装路径为可访问的网络地址
  pathWrap = path => apiUrl() + '/upload/' + path + '?r=' + new Date().getTime();

  // 气泡框图片
  popoverImage = (src = '', maxHeight = 128) => {
    const src0 = src.replace('_sm.','.');

    return src ? (
      <Popover
        trigger='click'
        placement="left"
        content={(
          <img
            src={this.pathWrap(src0)}
            alt=''
            style={{ maxWidth: '80vw', maxHeight: '80vh' }}
          />
        )}
      >
        <img src={this.pathWrap(src0)} style={{ maxHeight }} alt='' />
      </Popover>
    ) : null;
  };

  // 导出
  funcExport = () => {
    this.setState({ exporting: true });

    const { state } = this;
    const { searchs } = state;
    const { dispatch } = this.props;
    const payload = {
      currentPage: 1,
      pageSize: 10000,
      searchs,
    };

    if (state.currentNavi.length)
      payload.specialIds = state.currentNavi + '';

    dispatch({
      type: reqApi + '/listAll',
      payload,
    }).then(() => {
      this.setState({ exporting: false });

      const { props } = this;
      const { allData, counts } = props[reqApi];
      localStorage.setItem('studentData', JSON.stringify(allData));
      localStorage.setItem('studentCounts', JSON.stringify(counts));
      localStorage.setItem('studentTitle', state.currentTitle);

      const w = window.innerWidth, h = window.innerHeight;
      const win = window.open(
        'export.html',
        '_blank',
        'width=' + w + ',height=' + h + ',location=0,menubar=0,status=0,toolbar=0,scrollbars=1'
      );
      win.focus();
    });
  };

  // 打印
  funcPrint = (idStr) => {
    const { selectedRows, searchs } = this.state;

    let ids = idStr;
    if (!ids) {
      const idsData = [];
      for (let i = 0; i < selectedRows.length; i += 1) {
        const item = selectedRows[i];
        const { id } = item;
        idsData.push(id);
      }
      ids = idsData + '';
    }

    localStorage.setItem('ids', ids);
    localStorage.setItem('searchs', JSON.stringify(searchs));
    localStorage.setItem('action', 'gather');

    const w = window.innerWidth / 2, h = window.innerHeight;
    const win = window.open(
      'print.html?space=300',
      '_blank',
      'width=' + w + ',height=' + h + ',location=0,menubar=0,status=0,toolbar=0,scrollbars=1'
    );
    win.focus();
  };

  // 保存学生报名信息
  funcSave = () => {
    const { record } = this.state;
    const { form, dispatch } = this.props;

    form.validateFields((error, values) => {
      if (error) return error;

      const data = { ...values };
      data.id = record.id;
      if (values.birthday)
        data.birthday = values.birthday.format('YYYY-MM-DD');
      if (data.school === '其它学校')
        data.school = data.otherSchool || '其它学校';

      this.setState({ dialogLoading: true });

      dispatch({
        type: reqApi + '/edit',
        payload: { data },
      }).then(() => {
        this.setState({ dialogLoading: false });

        const { props } = this;
        const { success } = props[reqApi];
        if (success) {
          this.setState({ formVisible: false });
          this.funcGetListData();
        }
      });
    });
  };

  render() {
    const { state, props } = this;
    const { record, schoolData } = state;
    const { form } = props;
    const { getFieldDecorator } = form;
    const specSelectData = props[reqApi].specData[form.getFieldValue('pid')] || [];
    let typeSelectData = [];
    const specialId = form.getFieldValue('specialId');
    if (specialId) {
      for (let i = 0; i < specSelectData.length; i += 1) {
        const item = specSelectData[i];
        const { id, types } = item;
        if (id === specialId) {
          try {
            typeSelectData = JSON.parse(types);
          } catch(e) {
            typeSelectData = [];
          }
        }
      }
    }
    let drawerBodyPadding = 24;
    if (window.isPad) drawerBodyPadding = 16;
    if (window.isMobile) drawerBodyPadding = 0;

    const { status } = record;
    let st = statusMapping[status];
    st += '，审核员：' + record.auditAdminName;

    // 查询列
    const columnsSearch = [
      {
        title: '报考类别',
        dataIndex: 'type',
        type: 'select',
        sub: typeData,
      },
      {
        title: '是否住校',
        dataIndex: 'lodging',
        type: 'select',
        sub: [
          ['1', '住校'],
          ['0', '不住校'],
        ],
      },
      {
        title: '学生类别',
        dataIndex: 'situation',
        type: 'select',
        sub: [
          ['0', '应届'],
          ['1', '往届'],
        ],
      },
      {
        title: '学生姓名',
        dataIndex: 'name',
        type: 'text',
      },
      {
        title: '所在居住地',
        dataIndex: 'residType',
        type: 'select',
        sub: residTypeData.map((item) => {
          const { value, label } = item;
          return [value, label];
        }),
        onChange: value => {
          if (value === '-1') {
            this.setState({ schoolData: [] });
            return;
          }

          const schoolData = (residTypeMapping[value].children + ',其它学校')
            .split(',')
            .map(school => ([school, school]));
          this.setState({ schoolData });
        },
      },
      {
        title: '毕业学校',
        dataIndex: 'school',
        type: 'text',
        // sub: schoolData,
      },
      {
        title: '已交费日期',
        dataIndex: 'feeTime',
        type: 'date',
        startTime: '',
      },
    ];

    return (
      <PageHeaderLayout title={props.route.name}>
        <PageCard
          bodyStyle={{
            padding: 0,
            overflow: 'hidden',
          }}
          children={(
            <Layout>
              {window.isMobile ? null : (
                <Sider
                  theme='light'
                  width={260}
                  style={{ borderRight: '1px solid gainsboro' }}
                >
                  {this.naviMenu()}
                </Sider>
              )}
              <Content
                style={{
                  padding: '16px 8px 0 8px',
                  backgroundColor: 'white',
                }}
              >
                {this.contentTable()}
              </Content>
            </Layout>
          )}
        />

        <Drawer
          width={window.isMobile ? window.innerWidth : modalWidth}
          title={state.dialogTitle}
          visible={state.visible}
          onClose={() => this.setState({ visible: false })}
          bodyStyle={{ padding: drawerBodyPadding }}
          footerStyle={{ textAlign: 'right' }}
          footer={(
            <IconButton
              text='关闭'
              onClick={() => this.setState({ visible: false })}
            />
          )}
        >
          {window.isMobile ? null : (
            <div className={styles.title}>
              长治市职业高级中学招生登记表
            </div>
          )}
          <table className={styles.header}>
            <tbody>
            <tr>
              <td>
                <label>报名号</label>
                <span>{record.signup}</span>
              </td>
              <td align='right'>
                <label>准考证号</label>
                <span>{record.examCardNum}</span>
              </td>
            </tr>
            </tbody>
          </table>
          <table className={styles.table}>
            <tbody>
            <tr>
              <th>姓名</th><td>{record.name}</td>
              <th>性别</th><td>{record.sex ? '男' : '女'}</td>
              <td rowSpan={3}>
                {this.popoverImage(record.picture, 190)}
              </td>
            </tr>
            <tr>
              <th>出生日期</th><td>{record.birthday ? record.birthday.substr(0, 10) : ''}</td>
              <th>民族</th><td>{record.ethnic ? ethnicMapping[record.ethnic] : ''}</td>
            </tr>
            <tr>
              <th>学生类别</th><td>{situationMapping[record.situation]}</td>
              <th>电话</th>
              <td>
                <div>{record.phone}</div>
                <div>{record.phoneBackup}</div>
              </td>
            </tr>
            <tr>
              <th>中考成绩</th><td>{record.sum}</td>
              <th>身份证号</th><td colSpan={2}>{record.idCardNum}</td>
            </tr>
            <tr>
              <th>毕业学校</th><td>{record.school}</td>
              <th>家庭住址</th><td colSpan={2}>{record.address}</td>
            </tr>
            <tr>
              <th style={{ height: 128 }}>准考证</th>
              <td>
                {this.popoverImage(record.examCard)}
              </td>
              <th>身份证</th>
              <td>
                {this.popoverImage(record.idCardFace)}
              </td>
              <td>
                {this.popoverImage(record.idCardBack)}
              </td>
            </tr>
            <tr>
              <th colSpan={3}>报考专业</th><th>是否住校</th><th>备注</th>
            </tr>
            <tr>
              <td colSpan={3}>{record.specialName}</td>
              <td>{record.lodging ? '住校' : '不住校'}</td>
              <td>{record.remark}</td>
            </tr>
            <tr>
              <th colSpan={3}>所在居住地</th>
              <th colSpan={2}>特长</th>
            </tr>
            <tr>
              <td colSpan={3}>
                {residTypeMappingFull[record.residType] ?
                  residTypeMappingFull[record.residType].label : '外地'}
              </td>
              <td colSpan={2}>{record.speciality}</td>
            </tr>
            <tr>
              <th>推荐老师</th><td>{record.recommend}</td>
              <th>审核情况</th><td colSpan={3}>{st}</td>
            </tr>
            </tbody>
          </table>
        </Drawer>

        <Drawer
          width={window.isMobile ? window.innerWidth : modalWidth}
          title='选择专业'
          visible={state.visibleTree}
          onClose={() => this.setState({ visibleTree: false })}
          bodyStyle={{ padding: 0 }}
        >
          {this.naviMenu()}
        </Drawer>

        <Drawer
          width={window.isMobile ? window.innerWidth : modalWidth}
          title={(
            <div>
              <Icon type='tool' style={{ fontSize: 16 }} />
              <span> {'调整“' + record.name + '”的报名信息'}</span>
            </div>
          )}
          visible={state.formVisible}
          onClose={() => this.setState({ formVisible: false })}
          bodyStyle={{ paddingBottom: 0 }}
          footerStyle={{ textAlign: 'right' }}
          footer={[
            <IconButton
              key='cancel'
              text='取消'
              type='default'
              onClick={() => this.setState({ formVisible: false })}
            />,
            <IconButton
              key='save'
              text='保存'
              loading={state.dialogLoading}
              style={{ marginLeft: 8 }}
              onClick={this.funcSave}
            />,
          ]}
        >
          <Form>
            <Row gutter={{ md: 24, sm: 8 }}>
              <Col md={12} sm={24}>
                <Form.Item label='姓名' {...formItemLayout2}>
                  {getFieldDecorator('name', {
                    rules: [{ required: true, message: '请输入姓名' }],
                  })(<Input autoFocus maxLength={10} />)}
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label='性别' {...formItemLayout2}>
                  {getFieldDecorator('sex', { initialValue: '1' })(
                    <Radio.Group disabled>
                      <Radio value='1'>男</Radio>
                      <Radio value='0'>女</Radio>
                    </Radio.Group>
                  )}
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label="学生类别" {...formItemLayout2}>
                  {getFieldDecorator("situation", { initialValue: '0' })(
                    <Radio.Group buttonStyle="solid">
                      {situationData.map((item) => {
                        const { value, label } = item;
                        return <Radio.Button key={value} value={value}>{label}</Radio.Button>;
                      })}
                    </Radio.Group>
                  )}
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label="所在居住地" {...formItemLayout2}>
                  {getFieldDecorator("residType", { initialValue: '140403' })(
                    <Select
                      onChange={value =>
                        form.setFieldsValue({school: value === '0' ? '其它学校' : ''})
                      }
                    >
                      {residTypeData.map(item => {
                        const { value, label } = item;
                        return <Option key={value} value={value}>{label}</Option>;
                      })}
                    </Select>
                  )}
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label='毕业学校' {...formItemLayout2}>
                  {getFieldDecorator('school', {
                    rules: [{ required: true, message: '请选择毕业学校' }],
                  })(
                    <Select>
                      {form.getFieldValue('residType') !== '0' ?
                        (residTypeMapping[form.getFieldValue('residType')].children + ',其它学校')
                          .split(',').map(school =>
                          <Option key={school} value={school}>{school}</Option>
                        ) : <Option key='其它学校' value='其它学校'>其它学校</Option>
                      }
                    </Select>
                  )}
                </Form.Item>
              </Col>

              {form.getFieldValue('school') === '其它学校' ? (
                <Col md={12} sm={24}>
                  <Form.Item label='其它学校' {...formItemLayout2}>
                    {getFieldDecorator('otherSchool')(<Input maxLength={10} />)}
                  </Form.Item>
                </Col>
              ) : null}

              <Col md={12} sm={24}>
                <Form.Item label='家庭住址' {...formItemLayout2}>
                  {getFieldDecorator('address', {
                    rules: [{ required: true, message: '请输入家庭住址' }],
                  })(<Input maxLength={50} />)}
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label="手机号码" {...formItemLayout2}>
                  {getFieldDecorator("phone", {
                    rules: [{ required: true, validator: this.funcCheckPhone }],
                  })(<InputNumber min={0} max={19999999999} style={{ width: '100%' }} />)}
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label="家长电话" {...formItemLayout2}>
                  {getFieldDecorator("phoneBackup", {
                    rules: [{ required: false, validator: this.funcCheckPhoneBackup }],
                  })(
                    <InputNumber min={0} max={19999999999} style={{ width: '100%' }} />
                  )}
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label='身份证号' {...formItemLayout2}>
                  {getFieldDecorator('idCardNum', {
                    rules: [{ required: true, message: '请输入身份证号' }],
                  })(
                    <Input
                      maxLength={18}
                      onChange={e => {
                        const { value } = e.target;
                        if (value.length < 14) return;

                        const date = value.substr(6, 8);
                        const birthday = moment(date, 'YYYYMMDD');
                        form.setFieldsValue({ birthday });

                        if (value.length < 17) return;

                        const sex = value[16] % 2 + '';
                        form.setFieldsValue({ sex });
                      }}
                    />
                  )}
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label='准考证号' {...formItemLayout2}>
                  {getFieldDecorator("examCardNum")(
                    <InputNumber min={0} maxLength={9} style={{ width: '100%' }} />
                  )}
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label='报名号' {...formItemLayout2}>
                  {getFieldDecorator("signup")(
                    <InputNumber min={0} maxLength={12} style={{ width: '100%' }} />
                  )}
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label='中考成绩' {...formItemLayout2}>
                  {getFieldDecorator("sum")(
                    <InputNumber min={0} max={1000} step={10} style={{ width: '100%' }} />
                  )}
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label='系部' {...formItemLayout2}>
                  {getFieldDecorator('pid')(
                    <Select onChange={() => form.setFieldsValue({ specialId: '' })}>
                      {props[reqApi].sysData.map((item) => {
                        const { id, name } = item;
                        return <Option key={id} value={id}>{name}</Option>;
                      })}
                    </Select>
                  )}
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label="报考专业" {...formItemLayout2}>
                  {getFieldDecorator("specialId", {
                    rules: [{ required: true, message: '请选择报考专业' }],
                  })(
                    <Select>
                      {specSelectData.map((item) => {
                        const { id, name } = item;
                        return <Option key={id} value={id}>{name}</Option>;
                      })}
                    </Select>
                  )}
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label='报考类别' {...formItemLayout2}>
                  {getFieldDecorator('type', {
                    rules: [{ required: true, message: '请选择报考类别' }],
                  })(
                    <Radio.Group buttonStyle="solid">
                      {typeSelectData.map((type) => {
                        return (
                          <Radio.Button key={type + ''} value={type + ''}>
                            {types[type]}
                          </Radio.Button>
                        );
                      })}
                    </Radio.Group>
                  )}
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label="是否住校" {...formItemLayout2}>
                  {getFieldDecorator("lodging", { initialValue: '1' })(
                    <Radio.Group buttonStyle="solid">
                      <Radio.Button value='1'>住校</Radio.Button>
                      <Radio.Button value='0'>不住校</Radio.Button>
                    </Radio.Group>
                  )}
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label='民族' {...formItemLayout2}>
                  {getFieldDecorator('ethnic')(
                    <Select>
                      {ethnicData.map((item) => {
                        const { value, label } = item;
                        return <Option key={value} value={value}>{label}</Option>;
                      })}
                    </Select>
                  )}
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label="特长" {...formItemLayout2}>
                  {getFieldDecorator("speciality")(<Input maxLength={255} />)}
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label="免冠证件照" {...formItemLayout2}>
                  {getFieldDecorator("picture")(
                    <Input
                      disabled={state.pictureUploading}
                      suffix={
                        state.pictureUploading ? (
                          <Icon type="loading" />
                        ) : (
                          <Upload
                            accept="image/*"
                            showUploadList={false}
                            beforeUpload={(file) => {
                              if (state.pictureUploading) return false;
                              this.setState({
                                pictureUploading: true,
                                currentFile: 'picture',
                              }, () => this.funcCheckFile(file));
                            }}
                          >
                            <Tooltip title="选择图片">
                              <Icon type="upload" />
                            </Tooltip>
                          </Upload>
                        )
                      }
                    />,
                  )}
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label="准考证照片" {...formItemLayout2}>
                  {getFieldDecorator("examCard")(
                    <Input
                      disabled={state.examCardUploading}
                      suffix={
                        state.examCardUploading ? (
                          <Icon type="loading" />
                        ) : (
                          <Upload
                            accept="image/*"
                            showUploadList={false}
                            beforeUpload={(file) => {
                              if (state.examCardUploading) return false;
                              this.setState({
                                examCardUploading: true,
                                currentFile: 'examCard',
                              }, () => this.funcCheckFile(file));
                            }}
                          >
                            <Tooltip title="选择图片">
                              <Icon type="upload" />
                            </Tooltip>
                          </Upload>
                        )
                      }
                    />,
                  )}
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label="身份证正面" {...formItemLayout2}>
                  {getFieldDecorator("idCardFace")(
                    <Input
                      disabled={state.idCardFaceUploading}
                      suffix={
                        state.idCardFaceUploading ? (
                          <Icon type="loading" />
                        ) : (
                          <Upload
                            accept="image/*"
                            showUploadList={false}
                            beforeUpload={(file) => {
                              if (state.idCardFaceUploading) return false;
                              this.setState({
                                idCardFaceUploading: true,
                                currentFile: 'idCardFace',
                              }, () => this.funcCheckFile(file));
                            }}
                          >
                            <Tooltip title="选择图片">
                              <Icon type="upload" />
                            </Tooltip>
                          </Upload>
                        )
                      }
                    />,
                  )}
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label="身份证背面" {...formItemLayout2}>
                  {getFieldDecorator("idCardBack")(
                    <Input
                      disabled={state.idCardBackUploading}
                      suffix={
                        state.idCardBackUploading ? (
                          <Icon type="loading" />
                        ) : (
                          <Upload
                            accept="image/*"
                            showUploadList={false}
                            beforeUpload={(file) => {
                              if (state.idCardBackUploading) return false;
                              this.setState({
                                idCardBackUploading: true,
                                currentFile: 'idCardBack',
                              }, () => this.funcCheckFile(file));
                            }}
                          >
                            <Tooltip title="选择图片">
                              <Icon type="upload" />
                            </Tooltip>
                          </Upload>
                        )
                      }
                    />,
                  )}
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label='推荐教师' {...formItemLayout2}>
                  {getFieldDecorator("recommend", { initialValue: state.userName })(
                    <Input maxLength={10} />
                  )}
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label="备注" {...formItemLayout2}>
                  {getFieldDecorator("remark")(
                    <Input maxLength={255} />
                  )}
                </Form.Item>
              </Col>

              <Col span={0}>
                <Form.Item label="出生日期" {...formItemLayout2}>
                  {getFieldDecorator('birthday', {
                    initialValue: moment(),
                  })(
                    <DatePicker
                      format='YYYY-MM-DD'
                      style={{ width: '100%' }}
                      disabledDate={(now) => {
                        return now < moment('2000-01-01', 'YYYY-MM-DD') ||
                          now > moment().startOf('day');
                      }}
                    />
                  )}
                </Form.Item>
              </Col>

            </Row>
          </Form>
        </Drawer>

        <Drawer
          title='信息查询'
          placement='top'
          height='auto'
          bodyStyle={{ paddingBottom: 0 }}
          visible={state.visibleSearch}
          onClose={() => this.setState({ visibleSearch: false })}
        >
          <SearchForm
            fields={columnsSearch}
            onSubmit={this.funcOnSubmitSearch}
            autoSubmit={false} // 不自动提交表单, 只有点击了"查询"按钮才进行提交操作
          />
        </Drawer>

      </PageHeaderLayout>
    );
  }
}

const page2 = Form.create()(page);
export default connect(({ gather, menu }) => ({ gather, menu }))(page2);
